<?php
namespace app\common\controller;

use app\admin\model\Area;
use app\admin\model\Hospital;
use app\admin\model\School;
use app\admin\model\Student as StudentModel;
use app\common\model\Ent;
use app\common\model\Eyes;
use app\common\model\Fluoroscopy;
use app\common\model\Liver;
use app\common\model\Medicine;
use app\common\model\Stomatology;
use app\common\model\Surgery;
use auth\Auth;
use CodeItNow\BarcodeBundle\Utils\BarcodeGenerator;
use office\Excel;
use think\Db;
use think\facade\Config;
use think\facade\View;
use think\helper\Str;

class BaseAgent extends Base
{

    protected $auth_uid;    //后台管理员登录id
    protected $check_login = true;

    protected $model = null;
    protected $searchField = [];    //搜索字段

    public function initialize(){
        if ($this->check_login){
            $this->checkLogin();
        }
        $this->auth_uid =session(Config::get('login_agent')['auth_uid']);

        //记录操作日志
        admin_log($this->auth_uid?:0);
    }

    /**
     * 通用首页
     * @return array|string
     * @throws \Exception
     */
    public function index(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');
            $list = $this->model->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);
            //搜索器搜索模型自定义的字段
            if (count($this->searchField)>0){
                $data_list = [];
                foreach ($list as $k=>$v){
                    $data_list[$k] = $v;
                    foreach ($this->searchField as $field){
                        $data_list[$k][$field] = $v->$field;
                    }
                }
                return $this->tableJson($data_list,$list->total());
            }else{
                return $this->tableJson($list->getCollection(),$list->total());
            }
        }
        return $this->fetch();
    }

    /**
     * 通用回收站
     * @return array|string
     * @throws \Exception
     */
    public function recycle(){
        if ($this->request->isAjax()){
            //获取搜索条件
            $data =$this->request->except(['page'],'get');
            $list = $this->model->onlyTrashed()->withSearch($this->searchFields($data),$this->searchData($data))
                ->order('id','desc')
                ->paginate($data['limit'], false);
            //搜索器搜索模型自定义的字段
            if (count($this->searchField)>0){
                $data_list = [];
                foreach ($list as $k=>$v){
                    $data_list[$k] = $v;
                    foreach ($this->searchField as $field){
                        $data_list[$k][$field] = $v->$field;
                    }
                }
                return $this->tableJson($data_list,$list->total());
            }else{
                return $this->tableJson($list->getCollection(),$list->total());
            }
        }
        return $this->fetch();
    }

    /**
     * 通用软删除
     */
    public function remove(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            $this->model->destroy($ids);
            $this->success('删除成功');
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 通用彻底删除
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $this->model->destroy($ids, true);
            $this->success('删除成功');
        } else {
            $this->error('非法请求');
        }
    }

    /**
     * 恢复删除
     */
    public function recovery(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            $this->model->onlyTrashed()->whereIn('id',$ids)->select()->each(function($item){
                $item->restore();
            });
            $this->success('恢复成功');
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 通用更改状态
     * @return void
     */
    public function change(){
        if ($this->request->isAjax()){
            $id = $this->request->param('id');
            $state = $this->request->param('state');
            $res = $this->model->where('id',$id)->update(['state'=>$state]);
            if ($res){
                $this->success('操作成功');
            }else{
                $this->error('操作失败');
            }
        }else{
            $this->error('非法请求');
        }
    }



    /**
     * 是否登录否则跳转登录页面
     */
    protected function checkLogin(){
        $config = Config::get('login_agent');
        $auth_uid = session($config['auth_uid']);
        if (!$auth_uid){
            if ($this->request->isAjax()) {
                die("<script language='JavaScript'>location.href=".url($config['user_auth_gateway'])."</script>");
            }else {
                $this->redirect(url($config['user_auth_gateway']));
            }
        }
        return  $auth_uid;
    }


    /**
     * 模板变量赋值
     * @param $name
     * @param null $value
     */
    protected function assign($name, $value = null){
        View::assign($name,$value);
    }

    /**
     * 解析和获取模板内容 用于输出
     * @param string $template
     * @param array $vars
     * @return string
     * @throws \Exception
     */
    protected function fetch(string $template = '', array $vars = []){
        return View::fetch($template, $vars);
    }


    /**
     * 返回表格数据
     * @param $data
     * @param $total
     * @return array
     */
    protected function tableJson($data, $total,$extra = [])
    {
        $json = [
            'code' => 0,
            'msg' => '',
            'data' => $data,
        ];
        if ($total) {
            $json = array_merge($json, ['count' => $total]);
        }
        if ($extra) {
            $json = array_merge($json, $extra);
        }
        return $json;
    }


    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @return array
     */
    protected function searchFields($data){
        unset($data['limit']);
        unset($data['parent_id']);
        unset($data['level']);
        $data = array_keys($data);
        return $data;
    }

    /**
     * 配合withSearch搜索器使用
     * @param $data
     * @return array
     */
    protected function searchData($data){
        unset($data['limit']);
        unset($data['parent_id']);
        unset($data['level']);
        return $data;
    }

    /**
     * 加载搜索模型
     * @param $model
     * @return mixed
     */
    protected function loadSearchModel($field='user_id',$model = null){
        //加载模型
        if (empty($model)){
            $model = $this->model;
        }
        //是否存在搜索器，查询代理商下级
        $parent_id = $this->request->get('parent_id','');
        if (empty($parent_id)){
            $parent_id = $this->auth_uid;
        }
        //是否存在等级搜索
        $level = $this->request->get('level','');
        return $model->whereIn($field,function ($query) use ($parent_id,$level){
            if ($level){
                $query->name('user_child')->where('parent_id', $parent_id)->where('level',$level)->field('user_id');
            } else{
                $query->name('user_child')->where('parent_id', $parent_id)->field('user_id');
            }
        });
    }


}
